import { useState, useEffect } from 'react';
import {
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Button,
  List,
  ListItem,
  ListItemText,
  ListItemSecondaryAction,
  IconButton,
  TextField,
  CircularProgress,
  Alert,
  Box,
  Typography
} from '@mui/material';
import { Delete as DeleteIcon, Add as AddIcon } from '@mui/icons-material';
import { Resource } from '../../resources/types';
import { ResourceService } from '../../resources/services/ResourceService';
import { PromotionResourceService } from '../services/PromotionResourceService';

interface PromotionResourceFormProps {
  open: boolean;
  onClose: () => void;
  promotionId: string;
}

const PromotionResourceForm = ({ open, onClose, promotionId }: PromotionResourceFormProps) => {
  const [resources, setResources] = useState<Resource[]>([]);
  const [linkedResources, setLinkedResources] = useState<Resource[]>([]);
  const [searchQuery, setSearchQuery] = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (open) {
      fetchLinkedResources();
    }
  }, [open, promotionId]);

  const fetchLinkedResources = async () => {
    try {
      setLoading(true);
      setError(null);
      const resources = await PromotionResourceService.getPromotionResources(promotionId);
      setLinkedResources(resources);
    } catch (err) {
      setError(err instanceof Error ? err.message : '获取关联资源失败');
    } finally {
      setLoading(false);
    }
  };

  const handleSearch = async () => {
    if (!searchQuery.trim()) return;

    try {
      setLoading(true);
      setError(null);
      const results = await ResourceService.queryResources(searchQuery);
      setResources(results);
    } catch (err) {
      setError(err instanceof Error ? err.message : '搜索资源失败');
    } finally {
      setLoading(false);
    }
  };

  const handleAddResource = async (resource: Resource) => {
    try {
      setLoading(true);
      setError(null);
      await PromotionResourceService.createPromotionResource(promotionId, resource.id);
      await fetchLinkedResources();
      setResources(resources.filter(r => r.id !== resource.id));
    } catch (err) {
      setError(err instanceof Error ? err.message : '添加资源关联失败');
    } finally {
      setLoading(false);
    }
  };

  const handleRemoveResource = async (resourceId: string) => {
    try {
      setLoading(true);
      setError(null);
      await PromotionResourceService.deletePromotionResource(promotionId, resourceId);
      await fetchLinkedResources();
    } catch (err) {
      setError(err instanceof Error ? err.message : '删除资源关联失败');
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
      <DialogTitle>管理关联资源</DialogTitle>
      <DialogContent>
        {error && <Alert severity="error" sx={{ mb: 2 }}>{error}</Alert>}
        
        <Box sx={{ mb: 2 }}>
          <TextField
            fullWidth
            label="搜索资源"
            value={searchQuery}
            onChange={(e) => setSearchQuery(e.target.value)}
            onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
            sx={{ mb: 1 }}
          />
          <Button
            variant="contained"
            onClick={handleSearch}
            disabled={loading}
          >
            搜索
          </Button>
        </Box>

        <List>
          {resources.map((resource) => (
            <ListItem key={resource.id}>
              <ListItemText
                primary={resource.title}
                secondary={resource.description}
              />
              <ListItemSecondaryAction>
                <IconButton
                  edge="end"
                  onClick={() => handleAddResource(resource)}
                  disabled={loading}
                >
                  <AddIcon />
                </IconButton>
              </ListItemSecondaryAction>
            </ListItem>
          ))}
        </List>

        <Box sx={{ mt: 2 }}>
          <Typography variant="h6">已关联资源</Typography>
          <List>
            {linkedResources.map((resource) => (
              <ListItem key={resource.id}>
                <ListItemText
                  primary={resource.title}
                  secondary={resource.description}
                />
                <ListItemSecondaryAction>
                  <IconButton
                    edge="end"
                    onClick={() => handleRemoveResource(resource.id)}
                    disabled={loading}
                  >
                    <DeleteIcon />
                  </IconButton>
                </ListItemSecondaryAction>
              </ListItem>
            ))}
          </List>
        </Box>

        {loading && (
          <Box sx={{ display: 'flex', justifyContent: 'center', mt: 2 }}>
            <CircularProgress />
          </Box>
        )}
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>关闭</Button>
      </DialogActions>
    </Dialog>
  );
};

export default PromotionResourceForm;